package com.bit.bit_forum.controller;
import com.bit.bit_forum.common.AppResult;
import com.bit.bit_forum.common.ResultCode;
import com.bit.bit_forum.config.AppConfig;
import com.bit.bit_forum.model.User;
import com.bit.bit_forum.service.IUserService;
import com.bit.bit_forum.utils.MD5Util;
import com.bit.bit_forum.utils.StringUtil;
import com.bit.bit_forum.utils.UUIDUtil;
import io.micrometer.common.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    /**
     *
//    用户注册
     * @param username 用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @PostMapping("/register")
//                              此处是用注解对参数进行校验,也可以用下面的代码校验
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
      //1.参数校验
      if(StringUtils.isEmpty(username)
            || StringUtils.isEmpty(password)
            || StringUtils.isEmpty(nickname)
      || StringUtils.isEmpty(passwordRepeat)){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
          return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
      }
      //2.基本信息赋值
        User user = new User();
      user.setUsername(username);
      user.setNickname(nickname);
      user.setPassword(password);
      //对密码输入校验 ，判断密码与确认密码是否一致
        if(!password.equals(passwordRepeat)){
          log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
          return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //加密密码
        String salt = UUIDUtil.UUID_32();
        String psw = MD5Util.md5Salt(password,salt);
        user.setPassword(psw);
        user.setSalt(salt);
        userService.createNormUser(user);
        return AppResult.success();
    }

//    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest req,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //1.获取user对象
        User user = userService.login(username, password);
        //2.非空校验
        if(user==null){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //2.当登录成功时,把user对象设置到session作用域中
        HttpSession session = req.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }

    @RequestMapping("/info")
    public AppResult getById(HttpServletRequest req,
                             //                     这里设置require=false,表示id参数不是必传的
                             @ApiParam("用户id") @RequestParam(value="id" ,required=false) Long id){
        User user ;
        if(id==null){
//            当前详情为登陆者自己信息
            //当id为空时,从session中获取用户信息
            //若session不存在,说明未获取到用户信息,不要常见session
            HttpSession session = req.getSession(false);
            user = (User)session.getAttribute(AppConfig.USER_SESSION);
        }else{
            user = userService.getById(id);
        }
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }
    @RequestMapping("/logout")
    public AppResult logout(HttpServletRequest req){
        //1.获取session对象
        HttpSession session = req.getSession(false);
        if(session==null){
            //打印日志
            log.info("退出登录!");
            session.invalidate();
        }
        return AppResult.success("退出成功!");
    }

    @RequestMapping("/modifyInfo")
    public AppResult modifyUserInfo(HttpServletRequest req,
                                    @RequestParam(value="username",required = false) String username,
                                    @RequestParam(value="nickname",required = false) String nickname,
                                    @RequestParam(value="phoneNum",required = false) String phoneNum,
                                    @RequestParam(value="email",required = false) String email,
                                    @RequestParam(value="gender",required = false) Byte gender,
                                    @RequestParam(value="remark",required = false) String remark){
       //获取用户信息
        HttpSession session = req.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user==null || user.getDeleteStat()==1){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //非空校验:当所有参数全为空时,抛返回异常
        if(!StringUtil.isEmpty(username)
            &&!StringUtil.isEmpty(nickname)
            &&!StringUtil.isEmpty(phoneNum)
            &&!StringUtil.isEmpty(email)
            &&!StringUtil.isEmpty(remark)
            &&gender==null ){
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        User user1 = new User();
        user1.setId(user.getId());
        user1.setUsername(username);
        user1.setNickname(nickname);
        user1.setPhoneNum(phoneNum);
        user1.setEmail(email);
        user1.setGender(gender);
        user1.setRemark(remark);
        //跟新用户信息
        userService.updateUserInfo(user1);
        //重新获取用户信息
        User user2 = userService.getById(user.getId());
        //修改session中的用户信息:
        session.setAttribute(AppConfig.USER_SESSION,user2);
        return AppResult.success(user2);
    }

    @RequestMapping("/modifyPwd")
    public AppResult modifyUserPwd(HttpServletRequest req,
                                   @RequestParam("oldPassword") @NonNull  String oldPassword,
                                   @RequestParam("newPassword") @NonNull String newPassword,
                                   @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        HttpSession session = req.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user==null || user.getDeleteStat()==1){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        userService.updateUserPwd(user.getId(),oldPassword,newPassword);
        //修改密码后,让原来的session失效:
        if(session!=null){
            session.invalidate();
        }
        return AppResult.success();
    }

}
